<?php
/**
 *
 *
 */
class AuthenticateComponent extends Object
{

    public $controller;
    public $__tokens;
    public $tblUser        = "User";
    public $tblPrivilege   = "Privilege";
    public $tblRestriction = "RestrictionGrant";
    public $loginPage      = "/user/login";
    public $logoutPage     = "/ticket/start";
    public $redirectPage   = "/user/deny";

    public $components   = array('Session');


    /**
     * Constructor
     * @access protected
     */
    public function startup(&$controller)
    {
        $this->controller = $controller;
        if ($this->Session->valid() && $this->Session->check('User')) $this->__tokens = $this->Session->read('User');
        $this->controller->set('Authenticate', $this->__tokens);
    }

    /**
     * Validation of user and load grants based on
     * users privilege in session
     *
     * @params array $data
     * @return bool
     */
    public function validateToken(array $data)
    {
        $this->__tokens = $this->controller->{$this->tblUser}->authenticateUser($data);
        if ($this->__tokens) {
        	$restrictions = $this->controller->{$this->tblRestriction}->get_restriction_grants(array('privilegeId' => $this->__tokens['User']['privilege'], 'active' => 1));

            $this->Session->write('usersess', $this->__tokens);
            $this->Session->write('restrictions', $restrictions);
            return true;
        }

        return null;
    }

    public function validateResetPassword($pwd)
    {
        // get user info
        $condition = array('userId' => $pwd['userId'], 'token' => sha1($pwd['current']));
        $field = array('authId');
        $uInfo = $this->controller->{$this->tblUser}->getUserInfo($condition, $field);

        if ($uInfo) {
            if ($pwd['new'] == $pwd['confirm']) {
                return $this->controller->{$this->tblToken}->_save(array('token' => sha1($pwd['new'])), $uInfo[0]['User']['authId']);
            } else {
                return null;
            }
        } else {
            return null;
        }

    }

    public function resetPassword($userId)
    {
        // get user info
        $condition = array('userId' => $userId);
        $field = array('authId');
        $uInfo = $this->controller->{$this->tblUser}->getUserInfo($condition, $field);

        // generate password
        $new_password = $this->PasswordGenerator->generate();
        $hashed = sha1($new_password);

        // update current user with new password
        $result = $this->controller->{$this->tblToken}->_save(array('token' => $hashed), $uInfo[0]['User']['authId']);
        if ($result) {
            return $new_password;
        } else {
            return null;
        }
    }

    /**
     * @params string $redirect
     * @return void
     */
    public function logout($redirect = "")
    {
        $this->Session->delete('User');
        $page = (!empty($redirect)) ? $redirect : $this->loginPage;
        $this->controller->redirect($page);
    }

    /**
     * function
     */
    public function checkMyLogin($grant = 0, $bypass = false)
    {
        if ($this->Session->check('usersess') && $this->Session->check('restrictions')) {
            $session['usersess'] = $this->Session->read('usersess');
            $session['restrictions'] = $this->Session->read('restrictions');

            $access = $session['usersess']['User']['access'];
            $restrictions = $session['restrictions'];

            // check if user's restriction grants matches page restriction,
            // if not redirect to login page
            if ($grant) {
            	$success = true;
				foreach ($restrictions as $r) {
	            	if ($r['RestrictionGrant']['restrictionId'] == $grant) {
                        $success = true;
	            		break;
	            	} else {
	            		$success = false;
	            	}
	            }

	            if (!$success && !$bypass) {
                    $this->controller->redirect($this->redirectPage);
                }

                if ($success && $bypass) {
                    return true;
                } else {
                    return null;
                }
            }

            $this->controller->set('access', ($access)?strtolower($access):"annonymus");
            $this->controller->set('pId', self::myPrivilegeId());
        } else {
            $this->controller->redirect($this->redirectPage);
        }
    }

    public function getLoginPage()
    {
        return $this->loginPage;
    }

    public function getUserLoggedIn()
    {
        if ($this->Session->check('usersess')) {
            $session = $this->Session->read('usersess');
            $uid = $session['User']['userId'];
        } else {
            $uid = null;
        }

        return $uid;
    }

    public function myPrivilegeId()
    {
        return (!empty($this->__tokens)) ? $this->__tokens['User']['privilege'] : false;
    }
}
?>